package org.example.StudentManagementSystem.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.example.StudentManagementSystem.entity.Class;
import org.example.StudentManagementSystem.common.Result;
import org.example.StudentManagementSystem.dto.request.ClassDTO;
import org.example.StudentManagementSystem.service.ClassService;
import org.example.StudentManagementSystem.service.TeacherService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/class")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
@Tag(name = "班级管理", description = "班级管理相关的API接口")
public class ClassController {
    @Autowired
    private ClassService classService;
    @Autowired
    private TeacherService teacherService;

    /**
     * 将Class转换为DTO
     */
    public ClassDTO convertToDTO(Class clazz) {
        ClassDTO classDTO = new ClassDTO();
        BeanUtils.copyProperties(clazz, classDTO);
        if (clazz.getTeacherId() != null) {
            classDTO.setTeacherName(teacherService.getById(clazz.getTeacherId()).getName());
        }
        return classDTO;
    }

    /**
     * 获取班级列表
     */
    @Operation(summary = "获取班级列表", description = "根据页码和每页大小分页获取班级列表")
    @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = Result.class)), description = "获取班级列表成功")
    @ApiResponse(responseCode = "404", content = @Content(schema = @Schema(implementation = Result.class)), description = "暂无数据")
    @RequestMapping("")
    public Result getAllClass(
            @Parameter(description = "当前页码", required = true)
            @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页显示的班级数量", required = true)
            @RequestParam(defaultValue = "10") int size) {
        Page<Class> classPage = classService.page(Page.of(page, size));
        if (classPage.getTotal() == 0) {
            return Result.error("暂无数据");
        }
        List<ClassDTO> classDTOList = classPage.getRecords().stream().map(this::convertToDTO).collect(Collectors.toList());
        Page<ClassDTO> classDTOPage = new Page<>();
        classDTOPage.setCurrent(classPage.getCurrent());
        classDTOPage.setSize(classPage.getSize());
        classDTOPage.setTotal(classPage.getTotal());
        classDTOPage.setRecords(classDTOList);
        return Result.success(classDTOPage, "获取班级列表成功");
    }

    /**
     * 获取全部班级
     */
    @Operation(summary = "获取全部班级", description = "获取所有班级列表")
    @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = Result.class)), description = "获取班级列表成功")
    @ApiResponse(responseCode = "404", content = @Content(schema = @Schema(implementation = Result.class)), description = "暂无数据")
    @RequestMapping("/all")
    public Result getAllClass() {
        List<Class> classList = classService.list();
        if (classList.isEmpty()) {
            return Result.error("暂无数据");
        }
        List<ClassDTO> classDTOList = classList.stream().map(this::convertToDTO).collect(Collectors.toList());
        return Result.success(classDTOList, "获取班级列表成功");
    }

    /**
     * 获取单个班级详情
     */
    @Operation(summary = "获取单个班级详情", description = "根据班级ID获取班级详情")
    @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = Result.class)), description = "获取班级详情成功")
    @ApiResponse(responseCode = "404", content = @Content(schema = @Schema(implementation = Result.class)), description = "班级不存在")
    @RequestMapping("/{id}")
    public Result getClassById(
            @Parameter(description = "班级ID", required = true)
            @PathVariable int id) {
        Class clazz = classService.getById(id);
        if (clazz == null) {
            return Result.error("班级不存在");
        }
        ClassDTO classDTO = convertToDTO(clazz);
        return Result.success(classDTO, "获取班级详情成功");
    }

    /**
     * 添加班级
     */
    @Operation(summary = "添加班级", description = "添加一个新的班级")
    @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = Result.class)), description = "添加班级成功")
    @ApiResponse(responseCode = "400", content = @Content(schema = @Schema(implementation = Result.class)), description = "班级名称不能为空")
    @PostMapping("")
    public Result addClass(
            @Parameter(description = "班级信息", required = true)
            @RequestBody Class clazz) {
        if (clazz.getName() == null) {
            return Result.error("班级名称不能为空");
        }
        return classService.save(clazz) ? Result.success(clazz, "添加班级成功") : Result.error("添加班级失败");
    }

    /**
     * 修改班级
     */
    @Operation(summary = "修改班级", description = "根据班级ID修改班级信息")
    @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = Result.class)), description = "修改班级成功")
    @ApiResponse(responseCode = "400", content = @Content(schema = @Schema(implementation = Result.class)), description = "班级名称不能为空")
    @ApiResponse(responseCode = "404", content = @Content(schema = @Schema(implementation = Result.class)), description = "班级不存在")
    @PutMapping("/{id}")
    public Result updateClass(
            @Parameter(description = "班级ID", required = true)
            @PathVariable int id,
            @Parameter(description = "班级信息", required = true)
            @RequestBody Class clazz) {
        if (clazz.getName() == null) {
            return Result.error("班级名称不能为空");
        }
        clazz.setId(id);
        return classService.updateById(clazz) ? Result.success(clazz, "修改班级成功") : Result.error("修改班级失败");
    }

    /**
     * 删除班级
     */
    @Operation(summary = "删除班级", description = "根据班级ID删除班级")
    @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = Result.class)), description = "删除班级成功")
    @ApiResponse(responseCode = "404", content = @Content(schema = @Schema(implementation = Result.class)), description = "班级不存在")
    @DeleteMapping("/{id}")
    public Result deleteClass(
            @Parameter(description = "班级ID", required = true)
            @PathVariable int id) {
        if (classService.getById(id) == null) {
            return Result.error("班级不存在");
        }
        return classService.removeById(id) ? Result.success("删除班级成功") : Result.error("删除班级失败");
    }

    /**
     * 批量删除班级
     */
    @Operation(summary = "批量删除班级", description = "根据班级ID数组批量删除班级")
    @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = Result.class)), description = "批量删除班级成功")
    @ApiResponse(responseCode = "400", content = @Content(schema = @Schema(implementation = Result.class)), description = "请选择要删除的班级")
    @ApiResponse(responseCode = "404", content = @Content(schema = @Schema(implementation = Result.class)), description = "班级不存在")
    @DeleteMapping("")
    public Result deleteClasses(
            @Parameter(description = "班级ID数组", required = true)
            @RequestBody int[] ids) {
        if (ids.length == 0) {
            return Result.error("请选择要删除的班级");
        }
        for (int id : ids) {
            if (classService.getById(id) == null) {
                return Result.error("班级不存在");
            }
        }
        List<Integer> idList = Arrays.stream(ids).boxed().collect(Collectors.toList());
        return classService.removeBatchByIds(idList) ? Result.success("批量删除班级成功") : Result.error("批量删除班级失败");
    }
}
